<?php


use Phinx\Seed\AbstractSeed;
use Faker\Factory as FakerFactory;

class ChapterSeeder extends AbstractSeed
{
    public function getDependencies(): array
    {
        return [
            'CourseSeeder',
        ];
    }

    /**
     * Run Method.
     *
     * Write your database seeder using this method.
     *
     * More information on writing seeders is available here:
     * https://book.cakephp.org/phinx/0/en/seeding.html
     */
    public function run()
    {
        $courses = $this->fetchAll("SELECT * FROM kg_course");

        foreach ($courses as $course) {
            $rootCount = rand(1, 5);
            for ($i = 0; $i < $rootCount; $i++) {
                $rid = $this->generateCourse($course['id'], 0);

                $childCount = rand(1, 10);
                for ($j = 0; $j < $childCount; $j++) {
                    $this->generateCourse($course['id'], $rid);
                }
            }
        }
    }

    protected function generateCourse($courseId, $parentId = 0): string
    {
        $faker = FakerFactory::create('zh_CN');

        $time = $faker->unixTime;

        $data = [
            'parent_id' => $parentId,
            'course_id' => $courseId,
            'title' => $faker->text(15),
            'summary' => $faker->text(50),
            'priority' => 10,
            'free' => 0,
            'model' => 1,
            'attrs' => '{"duration":'.rand(50, 5000).',"file":{"status":"translated"}}',
            'published' => 1,
            'resource_count' => 0,
            'lesson_count' => 0,
            'user_count' => rand(0, 10000),
            'consult_count' => 0,
            'comment_count' => 0,
            'like_count' => rand(0, 10000),
            'create_time' => $time,
            'update_time' => $time,
        ];

        $this->table('kg_chapter')->insert([$data])->saveData();
        return $this->getAdapter()->getConnection()->lastInsertId();
    }

}
